<template>
  <div class="course_box" v-loading="loading">
    <div class="course_addbtn">
      <el-button icon="plus" @click="openAddDialog()" type="primary">
        新增课程
      </el-button>
      <span style="margin-left: 12px">学期：</span>
      <el-select
        v-model="coursePageParmas.semesterId"
        placeholder="请选择学期"
        clearable
        filterable
        @change="getCourseInfoPage()"
      >
        <el-option
          v-for="item in semesterOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </div>
    <el-table
      :data="courseDatas"
      border
      :header-row-style="{ color: '#232324', fontWeight: 'bold' }"
    >
      <el-table-column
        align="center"
        type="index"
        :index="indexMethod"
        label="序号"
        width="80"
      />
      <el-table-column
        align="center"
        label="课程名称"
        min-width="120"
        prop="courseName"
      />
      <el-table-column
        align="center"
        label="课程代码"
        min-width="120"
        prop="courseCode"
      />
      <el-table-column align="center" label="教师" min-width="120">
        <template #default="scope">
          <el-tag>{{ scope.row.teacher.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="学分"
        min-width="120"
        prop="credit"
      />
      <el-table-column
        align="center"
        label="开设学院"
        min-width="120"
        prop="department"
      />
      <el-table-column
        align="center"
        label="已选人数"
        min-width="180"
        prop="num"
      />
      <el-table-column
        align="center"
        label="最大可选人数"
        min-width="180"
        prop="maxNum"
      />
      <el-table-column
        align="center"
        label="状态"
        min-width="180"
        prop="status"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.status" type="success">可选</el-tag>
          <el-tag v-else type="danger">不可选</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="创建时间"
        min-width="180"
        prop="createTime"
      />
      <el-table-column
        align="center"
        label="更新时间"
        min-width="180"
        prop="updateTime"
      />
      <el-table-column align="center" fixed="right" label="操作" width="300">
        <template #default="scope">
          <el-button
            type="primary"
            link
            icon="edit"
            @click="openEditDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :icon="InfoFilled"
            icon-color="#626AEF"
            width="180"
            title="是否删除该课程?"
            @confirm="deleteCourseById(scope.row.id)"
          >
            <template #reference>
              <el-button type="primary" link icon="delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 12px"
      v-model:current-page="coursePageParmas.pageNum"
      v-model:page-size="coursePageParmas.pageSize"
      :page-sizes="[10, 20, 40]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      v-model="dialogFormVisible"
      :title="dialogTitle"
      style="min-width: 320px"
      @open="getOptions()"
    >
      <el-form
        v-if="dialogFormVisible"
        ref="courseForms"
        :inline="true"
        :model="courseForm"
        :rules="rules"
        label-position="top"
        label-width="85px"
      >
        <el-form-item label="课程名称" prop="courseName" style="width: 40%">
          <el-input
            v-model="courseForm.courseName"
            placeholder="请输入课程名称"
          />
        </el-form-item>
        <el-form-item label="课程编码" prop="courseCode" style="width: 40%">
          <el-input
            v-model="courseForm.courseCode"
            placeholder="请输入课程编码"
          />
        </el-form-item>
        <el-form-item label="教师" prop="teacherId" style="width: 40%">
          <el-select
            v-model="courseForm.teacherId"
            placeholder="请选择教师"
            filterable
          >
            <el-option
              v-for="item in teacherOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学期" prop="semesterId" style="width: 40%">
          <el-select
            v-model="courseForm.semesterId"
            placeholder="请选择学期"
            filterable
          >
            <el-option
              v-for="item in semesterOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学分" prop="credit" style="width: 40%">
          <el-input-number
            v-model="courseForm.credit"
            placeholder="请输入课程学分"
          />
        </el-form-item>
        <el-form-item label="开设学院" prop="department" style="width: 40%">
          <el-input
            v-model="courseForm.department"
            placeholder="请输入开设学院"
          />
        </el-form-item>
        <el-form-item label="最大可选人数" prop="maxNum" style="width: 40%">
          <el-input-number
            v-model="courseForm.maxNum"
            placeholder="请输入最大可选人数"
          />
        </el-form-item>
        <el-form-item label="课程描述" prop="description" style="width: 40%">
          <el-input
            :rows="4"
            maxlength="100"
            type="textarea"
            v-model="courseForm.description"
            placeholder="请输入课程描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="formConfirm(courseForms)">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import {
  reqAddCourse,
  reqDeleteCourseById,
  reqGetAllCourseByAdmin,
  reqGetTeacherOption,
  reqUpdateCourse,
} from '@/api/course'
import { CoursePageQuery, CourseParams, CourseType } from '@/api/course/type'
import { reqGetSemesterOption } from '@/api/semester'
import { OptionType } from '@/api/user/type'

onMounted(async () => {
  await getCourseInfoPage()
  await getSemesterOption()
})

const dialogFormVisible = ref<boolean>(false)
const coursePageParmas: CoursePageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
})
const courseDatas = ref<CourseType[]>()
const total = ref(0)
const loading = ref(false)
const semesterOptions = ref<OptionType[]>([])
const teacherOptions = ref<OptionType[]>([])
const courseForms = ref<FormInstance>()
let courseForm: CourseParams = reactive({
  courseId: 0,
  courseName: '',
  courseCode: '',
  teacherId: undefined,
  credit: 0,
  department: '',
  description: '',
  maxNum: 0,
  semesterId: undefined,
})

const rules = reactive({
  courseName: [{ required: true, message: '请输入课程名', trigger: 'blur' }],
  courseCode: [{ required: true, message: '请输入课程代码', trigger: 'blur' }],
  teacherId: [{ required: true, message: '请选择上课老师', trigger: 'blur' }],
  credit: [{ required: true, message: '请输入学分', trigger: 'blur' }],
  department: [{ required: true, message: '请输入开设学院', trigger: 'blur' }],
  maxNum: [{ required: true, message: '请输入最大可选人数', trigger: 'blur' }],
  semesterId: [{ required: true, message: '请选择学期', trigger: 'blur' }],
})

const indexMethod = (index: number) => {
  return index + (coursePageParmas.pageNum - 1) * coursePageParmas.pageSize + 1
}

// 添加菜单方法，id为 0则为添加根菜单
const dialogTitle = ref('新增课程')
const isEdit = ref(false)

const getCourseInfoPage = async () => {
  loading.value = true
  try {
    const { data } = await reqGetAllCourseByAdmin(coursePageParmas)
    courseDatas.value = data.list
    total.value = data.total
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false
  }
}

const getSemesterOption = async () => {
  try {
    const { data } = await reqGetSemesterOption()
    semesterOptions.value = data
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  }
}

const getTeacherOption = async () => {
  try {
    const { data } = await reqGetTeacherOption()
    teacherOptions.value = data
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  }
}

const getOptions = () => {
  if (teacherOptions.value.length === 0) {
    getTeacherOption()
  }
}

const deleteCourseById = async (id: number) => {
  try {
    const { message } = await reqDeleteCourseById(id)
    ElMessage.success(message)
    await getCourseInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const addCourse = async () => {
  try {
    const { message } = await reqAddCourse(courseForm)
    ElMessage.success(message)
    courseForm = {
      courseId: 0,
      courseName: '',
      courseCode: '',
      teacherId: undefined,
      credit: 0,
      department: '',
      description: '',
      maxNum: 0,
      semesterId: undefined,
    }
    await getCourseInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const updateCourse = async () => {
  try {
    const { message } = await reqUpdateCourse(courseForm)
    ElMessage.success(message)
    await getCourseInfoPage()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const formConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        updateCourse()
      } else {
        addCourse()
      }
      dialogFormVisible.value = false
    }
  })
}

const openAddDialog = () => {
  isEdit.value = false
  if (courseForm.courseId !== 0) {
    courseForm = {
      courseId: 0,
      courseName: '',
      courseCode: '',
      teacherId: undefined,
      credit: 0,
      department: '',
      description: '',
      maxNum: 0,
      semesterId: undefined,
    }
  }
  dialogTitle.value = '新增课程'
  dialogFormVisible.value = true
}
// 修改菜单方法
const openEditDialog = async (data: CourseType) => {
  isEdit.value = true
  dialogTitle.value = '编辑课程'
  courseForm.courseId = data.courseId
  courseForm.courseName = data.courseName
  courseForm.courseCode = data.courseCode
  courseForm.teacherId = data.teacher.id
  courseForm.credit = data.credit
  courseForm.department = data.department
  courseForm.description = data.description
  courseForm.maxNum = data.maxNum
  courseForm.semesterId = data.semester.id
  dialogFormVisible.value = true
}

const handleSizeChange = (val: number) => {
  getCourseInfoPage()
}
const handleCurrentChange = (val: number) => {
  getCourseInfoPage()
}
</script>
<style scoped lang="scss">
.course_box {
  padding: 24px;

  .course_addbtn {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
  }
}
</style>
